<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 警告提示区域 -->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数"
        type="warning"
        show-icon
        :closable="false"
      >
      </el-alert>
      <el-row>
        <el-col>
          选择商品分类：
          <!-- 级联选择框 -->
          <el-cascader
            v-model="selectedCateKeys"
            :options="cateList"
            :props="cateProps"
            @change="cateChanged"
            clearable
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- tab页签区域，v-model双向绑定页签中的name属性 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <!-- 此处disabled的逻辑就是当没有选择级联菜单时（数组长度为0，转换为true）
          或者就是定义一个计算属性，判断selectedCateKeys数组长度是否为0，返回true或者false，绑定到disabled上
          ，按钮处于禁用状态 -->
          <el-button
            type="primary"
            size="mini"
            :disabled="this.selectedCateKeys.length === 0"
            @click="addDialogVisible = true"
            >添加参数</el-button
          >
          <!-- 渲染动态参数表格 -->
          <el-table :data="manyTableData" border stripe>
            <el-table-column type="expand">
              <!-- 展开项数据来源：attr-vals
                分割为数组-for循环渲染
                 -->
              <template slot-scope="scope">
                <!--循环标签渲染  -->
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="handleClose(index, scope.row)"
                  >{{ item }}</el-tag
                >
                <!-- 添加标签的输入框 v-if-->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 输入框失去焦点之后 v-else-->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"> </el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <!-- 修改按钮 -->
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row.attr_id)"
                ></el-button>
                <!-- 删除按钮 -->
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeParams(scope.row.attr_id)"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="this.selectedCateKeys.length === 0"
            @click="addDialogVisible = true"
            >添加属性</el-button
          >
          <!-- 渲染静态参数表格 -->
          <el-table :data="onlyTableData" border stripe>
            <el-table-column type="expand">
              <!-- 展开项数据来源：attr-vals
                分割为数组-for循环渲染
                 -->
              <template slot-scope="scope">
                <!--循环标签渲染  -->
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="handleClose(index, scope.row)"
                  >{{ item }}</el-tag
                >
                <!-- 添加标签的输入框 v-if-->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 输入框失去焦点之后 v-else-->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"> </el-table-column>
            <el-table-column prop="attr_name" label="属性名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <!-- 修改按钮 -->
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row.attr_id)"
                ></el-button>
                <!-- 删除按钮 -->
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeParams(scope.row.attr_id)"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加动态参数/静态属性对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClose"
    >
      <!-- 添加的表单数据 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改动态参数/静态属性对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClose"
    >
      <!-- 修改的表单数据 -->
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 数据列表
      cateList: [],
      //数据源配置项
      cateProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
        expandTrigger: "hover",
      },
      //   级联选择框选中的节点id存储的地方
      selectedCateKeys: [],
      //被激活的页签页面，默认为第一个
      activeName: "many",
      //动态数据参数
      manyTableData: [],
      //动态数据参数
      onlyTableData: [],
      //控制添加对话框的显示与隐藏
      addDialogVisible: false,
      //添加表单的数据对象
      addForm: {
        attr_name: "",
      },
      //添加表单的验证规则
      addFormRules: {
        attr_name: [
          { required: true, message: "请输入详细信息", trigger: "blur" },
        ],
      },
      //控制编辑对话框的显示与隐藏
      editDialogVisible: false,
      //编辑表单的数据对象
      editForm: {},
      //编辑表单的验证规则
      editFormRules: {
        attr_name: [
          { required: true, message: "请输入详细信息", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    //   获取所有商品列表
    async getCateList() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200) {
        return this.$message.error("获取父级分类列表失败");
      }
      this.cateList = res.data;
    },
    async cateChanged() {
      this.getParamsData();
    },
    // 当页签发生切换的点击事件时
    handleTabClick() {
      this.getParamsData();
    },
    async getParamsData() {
      console.log(this.cateId);
      //根据所选分类的最后一级id和当前所处的面板获取商品参数
      //即：级联选择器的选择发生改变以及面板切换时都调用该函数
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        { params: { sel: [this.activeName] } }
      );
      if (res.meta.status !== 200) {
        this.$message.error("获取三级分类商品参数失败");
      }
      console.log(res.data);
      //拿到的数据里的attr-val转变为数组，方便后续展开行渲染
      res.data.forEach((item) => {
        //此处不应该直接赋值，而是应该判断有没有attr_vals值
        item.attr_vals = item.attr_vals ? item.attr_vals.split(",") : [];
        // 给每一个遍历出来的值都加上inputVisible和inputValue
        // 防止每个展开行的输入框都出现联动效果
        item.inputVisible = false;
        item.inputValue = "";
      });
      //判断拿到的数据是静态还是动态
      if (this.activeName == "many") {
        this.manyTableData = res.data;
      } else {
        this.onlyTableData = res.data;
      }
    },
    // 监听在对话框关闭的时候清空信息
    addDialogClose() {
      this.$refs.addFormRef.resetFields();
    },
    // 点击确定按钮，添加参数
    addParams() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          { attr_name: this.addForm.attr_name, attr_sel: [this.activeName] }
        );
        if (res.meta.status !== 201) {
          return this.$message.error("添加参数失败");
        }
        this.$message.success("添加参数成功");
        this.addDialogVisible = false;
        this.getParamsData();
      });
    },
    async showEditDialog(attr_id) {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${attr_id}`,
        { params: { attr_sel: [this.activeName] } }
      );
      if (res.meta.status !== 200) {
        return this.$message.error("根据id获取参数失败");
      }
      this.editForm = res.data;
      this.editDialogVisible = true;
    },
    // 监听在编辑对话框关闭的时候清空信息
    editDialogClose() {
      this.$refs.editFormRef.resetFields();
    },
    // 点击确定按钮，修改参数
    editParams() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
          { attr_name: this.editForm.attr_name, attr_sel: [this.activeName] }
        );
        if (res.meta.status !== 200) {
          return this.$message.error("修改参数失败");
        }
        this.$message.success("修改参数成功");
        this.editDialogVisible = false;
        this.getParamsData();
      });
    },
    // 点击删除按钮，删除参数
    async removeParams(attr_id) {
      const confirmResult = await this.$confirm(
        "此操作将永久删除该参数, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (confirmResult == "取消") {
        return this.$message.info("删除参数行为取消");
      }
      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${attr_id}`,
        {}
      );
      if (res.meta.status !== 200) {
        return this.$message.error("删除参数行为失败");
      }
      this.$message.success("删除参数行为成功");
      this.getParamsData();
    },
    async handleInputConfirm(row) {
      // 此处不应直接隐藏对话框，而是应该判断输入的内容是否有效
      // 无效的话，返回出去；有效再进一步调用接口进行添加
      if (row.inputValue.trim().length == 0) {
        row.inputValue = "";
        row.inputVisible = false;
        return;
      }
      row.attr_vals.push(row.inputValue.trim());
      row.inputValue = "";
      row.inputVisible = false;
      // 发起请求提交数据
      this.saveAttrs(row);
    },
    async saveAttrs(row) {
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(","),
        }
      );
      if (res.meta.status !== 200) {
        return this.$message.error("修改展开行参数失败");
      }
      this.$message.success("修改展开行参数成功");
    },
    showInput(row) {
      row.inputVisible = true;
      //使文本框自动获取焦点
      //$nextTick的作用是当页面上的元素被重新渲染时，执行回调里面的代码
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    handleClose(index, row) {
      //删掉相应参数，然后调用接口提交到服务器上
      row.attr_vals.splice(index, 1);
      this.saveAttrs(row);
    },
  },
  computed: {
    //   计算出当前选中的最后一级id
    cateId() {
      if (this.selectedCateKeys !== 0) {
        return this.selectedCateKeys[this.selectedCateKeys.length - 1];
      }
      return null;
    },
    titleText() {
      if (this.activeName == "many") {
        return "动态参数";
      }
      return "静态属性";
    },
  },
};
</script>

<style scoped>
.el-row {
  margin: 15px 0;
}
.el-tag {
  margin: 5px;
}
.input-new-tag {
  width: 120px;
}
</style>